﻿using System;

namespace Gonte.Validation
{
    /// <summary>
    /// Defines the common functionality for the field validation implementors
    /// </summary>
    public class FieldValidator
    {
        #region Constants

        private const string DifferentTypes = "The type to validate against: {0} does not correspond with the type of the object: {1}"; 

        #endregion

        #region Methods

        public FieldValidator()
        {
        }

        public FieldValidator(Type type)
        {
            type_ = type;
        }

        public virtual bool Validate(Object value)
        {
            return CanValidate(value);
        }

        #endregion

        #region Properties

        public string Error
        {
            get { return error_; }
            //set { error_ = value; }
        }

        public Type Type
        {
            get { return type_; }
            set { type_ = value; }
        }

        #endregion

        #region Helpers

        private bool CanValidate(Object value)
        {
            if (value == null)
            {
                return true;
            }

            if (type_ != null
                && type_ != value.GetType())
            {
                error_ = string.Format(DifferentTypes, type_, value.GetType());
                return false;
            }
            return true;
        } 

        #endregion

        #region Attributes

        private Type type_;
        protected string error_;  // The error message when the validation fails 

        #endregion
    }
}
